package park.gz.com.parkingfee.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import park.gz.com.parkingfee.R;
import park.gz.com.parkingfee.adapter.SelectListAdapter;
import park.gz.com.parkingfee.adapter.SelectListAdapter.OnItemClickListener;
import park.gz.com.parkingfee.bean.UserBean;
import park.gz.com.parkingfee.until.GetImei;
import park.gz.com.parkingfee.until.ShareUtil;


public class MainActivity extends Activity implements OnItemClickListener, OnDismissListener {
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.input_password)
    EditText inputPassword;
    @Bind(R.id.miei)
    TextView miei;
    @Bind(R.id.btn_commit)
    TextView btn_commit;
    private RelativeLayout mInputLayout;
    private ImageButton mArrow;
    private TextView mInput;
    private PopupWindow mSelectWindow;
    private LayoutInflater mInflater;
    private List<UserBean> userinfolist;
    private SelectListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initView() {
        mInputLayout = (RelativeLayout) findViewById(R.id.input_layout);
        mArrow = (ImageButton) findViewById(R.id.input_arrow);
        mInput = (TextView) findViewById(R.id.input_et);
        userinfolist = new ArrayList<UserBean>();
        miei.setText("终端号:" + GetImei.getphoneimei(MainActivity.this));

    }

    private void initData() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        down_front_user();
    }

    public void onDownArrowClicked(View view) {
        if (userinfolist.size() != 0) {
            mArrow.setBackgroundResource(R.drawable.arrow_up);
            showAccountChoiceWindow();
        }
    }

    private void showAccountChoiceWindow() {
        View view = mInflater.inflate(R.layout.input_selectlist, null);
        RelativeLayout contentview = (RelativeLayout) view.findViewById(R.id.input_select_listlayout);
        ListView userlist = (ListView) view.findViewById(R.id.input_select_list);
        userlist.setDividerHeight(0);

        adapter = new SelectListAdapter(MainActivity.this, userinfolist);
        adapter.setOnItemClickListener(this);
        //adapter.setOnDelBtnClickListener(this);
        userlist.setAdapter(adapter);

        mSelectWindow = new PopupWindow(contentview, mInputLayout.getMeasuredWidth(), LayoutParams.WRAP_CONTENT, true);
        mSelectWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_input_bottom_normal));
        mSelectWindow.setOutsideTouchable(true);
        mSelectWindow.setFocusable(true);
        mSelectWindow.setOnDismissListener(this);
        mSelectWindow.showAsDropDown(mInputLayout, 0, 0);
        mArrow.setBackgroundResource(R.drawable.arrow_up);
    }

/*     @Override
   public void onDelBtnClicked(int position) {
        mSelectWindow.dismiss();
        String inputAccount = mInput.getText().toString();
        if (inputAccount == userinfolist.remove(position).getLogin()) {
            String nextAccount = "";

            if (userinfolist.size() != 0)
                nextAccount = userinfolist.get(0) + "";

            mInput.setText(nextAccount);
        }
        Toast.makeText(this, "删除账号成功", Toast.LENGTH_SHORT).show();
    }*/

    @Override
    public void onItemClicked(int position) {
        mSelectWindow.dismiss();
        mInput.setText(userinfolist.get(position).getLogin() + "");
    }

    @Override
    public void onDismiss() {
        mArrow.setBackgroundResource(R.drawable.arrow_down);
    }

    @OnClick({R.id.btn_login,R.id.btn_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                if ("".equals(mInput.getText().toString().trim()) || "".equals(inputPassword.getText().toString().trim())) {
                    Toast.makeText(MainActivity.this, "用户名或密码不能为空", Toast.LENGTH_LONG).show();
                } else {
                    if (ifhaveBean(userinfolist)) {
                        Intent intent = new Intent(MainActivity.this, ParkActivity.class);
                        startActivity(intent);
                        ShareUtil.setstringvalue(this, MyAppcation.userName, mInput.getText().toString().trim());
                    } else {
                        Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_LONG).show();
                    }
                }

                break;
            case R.id.btn_commit:
                createDialog();
                break;
        }
    }

    public boolean ifhaveBean(List<UserBean> list) {
        if (list.size() == 0 || list == null) {
            return false;
        }
        for (int i = 0; i < list.size(); i++) {
            if (mInput.getText().toString().trim().equals(list.get(i).getLogin()) && inputPassword.getText().toString().trim().equals(list.get(i).getPassword())) {
                return true;
            }
        }
        return false;
    }

    private void down_front_user() {

        String url = ShareUtil.getstringvalue(MainActivity.this,"baseurl") + "/api/v1/down_front_user";
        RequestParams params = new RequestParams(url);
        params.addParameter("controller_sn", GetImei.getphoneimei(this));//终端编号
        params.addParameter("max_updated_at", "2015-01-01");//时间戳
        Log.i("duzhijuan", params + "");
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("0".equals(jsonObject.getString("ref"))) {
                        userinfolist.clear();
                        String user = jsonObject.getJSONArray("result").toString();
                        String saveuserinfo = ShareUtil.getstringvalue(MainActivity.this, MyAppcation.userInfo);
                        if ("".equals(saveuserinfo) || !user.equals(saveuserinfo)) {
                            ShareUtil.setstringvalue(MainActivity.this, MyAppcation.userInfo, user);
                            userinfolist.addAll(UserBean.parse(jsonObject.getJSONArray("result")));
                        } else {
                            userinfolist.addAll(UserBean.parse(new JSONArray(saveuserinfo)));
                        }
                        mInput.setText(userinfolist.get(0).getLogin());
                    } else {
                        Toast.makeText(MainActivity.this, jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("my", "onError" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.e("my", "onCancelled" + cex.toString());
            }

            @Override
            public void onFinished() {
                Log.e("my", "onFinished");
            }

        });
    }

    private void createDialog() {

        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        View view = LayoutInflater.from(this).inflate(R.layout.activity_choiceurl, null);
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();
        final EditText editText = (EditText) view.findViewById(R.id.et_url);
        TextView btn_ok = (TextView) view.findViewById(R.id.btn_ok);
        TextView btn_cancle = (TextView) view.findViewById(R.id.btn_cancle);
        DisplayMetrics metrics=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int widthPixels=metrics.widthPixels;
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = widthPixels-100;
       // params.height = 800;
        dialog.getWindow().setAttributes(params);
        btn_cancle.setOnClickListener(new View.OnClickListener() {//点击取消按钮

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();

            }
        });
        btn_ok.setOnClickListener(new View.OnClickListener() {//点击确认按钮

            @Override
            public void onClick(View arg0) {
                ShareUtil.setstringvalue(MainActivity.this,"baseurl",editText.getText().toString().trim());
                down_front_user();
                dialog.dismiss();

            }
        });
    }
}
